import PAY_BG from '@/assets/vip/pay-bg.png'
import {setDescription, setFavicon, setKeyWord} from "@/util/webSiteConfigUtil";
import Logo from "@/assets/system/logo.svg"

/**
 *  全局状态码
 */
export const ECode = {
    // 默认页大小
    SUCCESS: "success",
    // 默认页码
    ERROR: "error",
    // 微信轮询
    WECHAT_POLLING: "校验失败，请扫码登录",
};

export const errorCode = {
    401: 'Token无效或过期,请重新登录',
    402: '当前操作没有权限',
    403: '当前操作没有权限',
    404: '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
};

export const PagePath = {
    // 关于我
    About: '/about',
    // 搜索结果页
    ResultsPath: '/results',
    // 用户中心
    UserCenterPath: '/userCenter',
    // 文章详情
    PostInfoPath: '/post/',
    // 徽章
    MedalPath: '/medal/',
    // 签到
    SignPath: '/user/sign',
    // 众言
    MessageBoardPath: '/messageBoard',
    // 文章归档
    SortPath: '/sort',
    // 众星
    FriendsPath: '/friends',
    // 热搜
    Hot: '/hot',
    // 会员中心
    Vip: '/vip',
    // 问答
    Question: '/question',
    // 瞬间
    Moment: '/moment',
    // 小店
    Mall: '/mall',
    // 专题
    Subject: '/subject',
    // 排行榜
    Rank: '/rank',
    // 面经
    Code: '/code',
    // 通知
    Notice: '/notice',
    // 赞助
    Sponsor: '/sponsor',
    // 抽奖
    Lucky: '/lucky',
    // 足迹
    Map: '/footprint'
}

export const defaultSummary = '系统默认签名，送给每一个用户！'

// 自定义引入的iconfont图标
export const iconFontAddress = '//at.alicdn.com/t/c/font_4740515_jyqi5fvrbk.js'

export const EAction = {
    // 点赞
    Praise: "Praise",
    // 点踩
    Tread: "Tread",
    // 收藏
    Collect: "Collect",
    // 评论
    Comment: "Comment",
    // 支付
    Pay: "Pay",
}

/**
 * 设置网页的元信息
 */
export function setMetaInfo(title: string, content: string, description: string, logoPhoto: string): void {
    document.title = title
    if (content) {
        setKeyWord(content)
    }
    if (description) {
        setDescription(description)
    }
    if (logoPhoto) {
        setFavicon(logoPhoto)
    } else {
        setFavicon(Logo)
    }

}

export function setPostMetaInfo(title: string, content: string, description: string): void {
    document.title = title
    if (content) {
        setKeyWord(content)
    }
    if (description) {
        setDescription(description)
    }
}

/** 写入网页标题 */
export function setDocumentTitle(title: string): void {
    document.title = title;
}

/**
 * 初始化用户权限码
 *
 * @param authCodeJson 权限码的 JSON 字符串
 * @returns 用户权限映射
 */
export function InitUserAuthCode(authCodeJson: any) {
    // 初始化定义权限
    const authCodeMap = {
        BLOG_AUDIT: false,
        UPLOAD_BLOG: false,
        ADD_COMMENT: false,
        ADD_BLOG: false,
        ADD_QUESTION: false,
        ADD_MOMENT: false,
        ADD_PROBLEM: false,
        PUBLIC_CHAT: false,
        PRIVATE_CHAT: false,
    };
    // 定义默认的权限
    if (!authCodeJson) {
        authCodeMap.ADD_COMMENT = true;
        authCodeMap.ADD_BLOG = true;
        authCodeMap.ADD_QUESTION = true;
        authCodeMap.ADD_MOMENT = true;
        authCodeMap.ADD_PROBLEM = true;
        authCodeMap.PUBLIC_CHAT = true;
        authCodeMap.PRIVATE_CHAT = true;
        return authCodeMap;
    }
    try {
        const authCodeList: string[] = JSON.parse(authCodeJson);
        authCodeList.forEach((item) => {
            if (item in authCodeMap) {
                //@ts-ignore
                authCodeMap[item] = true;
            }
        });
    } catch (error) {
        console.error('解析 authCodeJson 失败:', error);
    }
    return authCodeMap;
}

/**
 * 计算给定开始时间到当前时间的时间差（以天为单位）
 *
 * @param startTime 开始时间的字符串表示，格式为 'YYYY-MM-DD'
 * @returns 从开始时间到当前时间的天数差
 */
export function calculateTimeDifference(startTime: string): number {
    // 获取当前时间
    const endDate = new Date();
    // 将时间字符串转换为 Date 对象
    const startDate = new Date(startTime.replace(/-/g, '/'));
    // 计算时间差（毫秒）
    const timeDifference = endDate.getTime() - startDate.getTime();
    // 将时间差转换为天
    return Math.floor(timeDifference / (1000 * 60 * 60 * 24));
}

export function checkDiscount(entity: any) {
    // 格式化时间
    let now = new Date().getTime() / 1000;
    let discountStartTime = 0;
    let discountEndTime = 0;
    if (entity.discountStartTime) {
        discountStartTime = new Date(entity.discountStartTime).getTime() / 1000;
    }
    // 判断折扣时间
    if (entity.discountEndTime) {
        discountEndTime = new Date(entity.discountEndTime).getTime() / 1000;
    }
    // 判断是否处于折扣时间内
    return now > discountStartTime && now < discountEndTime;
}

export function convertVip(entity: any) {
    let product = {
        images: PAY_BG,
        chargeType: entity.chargeType, // 默认付费
        title: entity.name,
        summary: entity.summary.substring(0, 40),
        price: entity.price,
        discountPrice: entity.discountPrice,
        resourceType: "VIP",
        effectDay: entity.effectDay,
        resourceUid: entity.uid,
        payType: entity.payType, // 支付方式，积分支付或现金支付
        payOrderCount: entity.payOrderCount ? entity.payOrderCount : 0, // 支付的订单数
        betweenDiscount: false,
        discountStartTime: '',
        discountEndTime: ''
    };
    // 如果不是折扣价，那么就要保持 price 和 discountPrice 价格一致
    if (entity.chargeType !== 3) {
        product.discountPrice = product.price;
    }
    // 格式化时间
    let now = new Date().getTime() / 1000;
    let discountStartTime = 0;
    let discountEndTime = 0;
    if (entity.discountStartTime) {
        discountStartTime = new Date(entity.discountStartTime).getTime() / 1000;
        product.discountStartTime = discountStartTime + " ";
    }
    // 判断折扣时间
    if (entity.discountEndTime) {
        discountEndTime = new Date(entity.discountEndTime).getTime() / 1000;
        product.discountEndTime =
            new Date(entity.discountEndTime).getTime() / 1000 + " ";
    }
    // 判断是否处于折扣时间内
    if (now > discountStartTime && now < discountEndTime) {
        product.betweenDiscount = true;
    }
    return product;
}

export function replaceFromEnd(str: string, oldStr: string, newStr: string) {
    let index = str.lastIndexOf(oldStr);
    if (index === -1) {
        return str;
    }
    let before = str.slice(0, index);
    let after = str.slice(index).replace(oldStr, newStr);
    return before.concat(after);
}

export function moveCursorToEnd(inputBox: HTMLDivElement, isEnd: boolean) {
    let targetIndex = isEnd ? inputBox.children.length - 1 : 0;
    let targetElement = inputBox.children[targetIndex];
    if (!targetElement || targetElement.nodeType === Node.TEXT_NODE) {
        const newElement = document.createElement("span");
        if (isEnd) {
            inputBox.appendChild(newElement);
        } else {
            inputBox.insertBefore(newElement, inputBox.firstChild);
        }
        targetElement = newElement;
    }
    const range = document.createRange();
    let selection: any = window.getSelection();
    range.selectNodeContents(targetElement);
    range[isEnd ? "setEnd" : "setStart"](
        targetElement,
        targetElement.childNodes.length,
    );
    range.collapse(isEnd);
    selection.removeAllRanges();
    selection.addRange(range);
}

export function replaceMinImg(str: string) {
    let containChatImg = false;
    str = str.replace(/(<img[^>]*>)|(<img[^>]*><\/img>)/g, function (
        match
    ) {
        // 包含了聊天表情，不替换
        if (
            match.indexOf("chat-msg-img") >= 0 ||
            match.indexOf("chat-msg-emoji") >= 0
        ) {
            containChatImg = true;
            return match;
        }
        if (match.indexOf("style") < 0) {
            // 没有style 就添加一个
            return match.replace(/<\s*img/, '<img style=""');
        } else {
            // 有style 就不做处理 直接返回
            return match;
        }
    });

    if (containChatImg) {
        return str;
    }
    str = str.replace(/<img[^>]*>/gi, function (match) {
        return match.replace(
            /style\s*?=\s*?([‘"])[\s\S]*?\1/gi,
            'style="max-height: 300px; display:block;"',
        ); // 替换style
    });
    return str;
}

export function replaceMinIframe(str: string) {
    str = str.replace(/(<iframe[^>]*>)|(<iframe[^>]*><\/iframe>)/g, function (
        match,
    ) {
        if (match.indexOf("style") < 0) {
            // 没有style 就添加一个
            return match.replace(/<\s*iframe/, '<iframe style=""');
        } else {
            // 有style 就不做处理 直接返回
            return match;
        }
    });
    str = str.replace(/<iframe[^>]*>/gi, function (match) {
        return match.replace(
            /style\s*?=\s*?([‘"])[\s\S]*?\1/gi,
            'style="width: 740px; height: 400px; display:block;"',
        ); // 替换style
    });
    return str;
}

export function commonConsoleLog(content: string) {
    console.log(`%c ${content}`, "color:#fff; background: linear-gradient(270deg, #18d7d3, #68b7dd, #8695e6, #986fee); padding: 8px 15px; border-radius: 8px")
}

export function AppConsoleLog() {
    console.log(`%c🎉架构于：Vite + Vue3 + TypeScript | 作者：生产队的驴 | 仓库地址：https://gitee.com/yanhexo`,
        "color:#fff; background: linear-gradient(272.01deg, #73ccff 0%, #adbfff 50.31%, #ffdaf9 100%); " +
        "padding: 8px 15px; " +
        "border-radius: 8px;" +
        "color:black;" +
        "font-weight:600;" +
        "font-family:HarmonyOSHans-Regular");
}

export function randomUUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        const r = (Math.random() * 16) | 0,
            v = c === "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

export default {
    ECode,
    errorCode,
    PagePath,
    replaceMinImg,
    replaceMinIframe
}
